<template>
  <a-layout class="positionBox page_set page-miH page-bgBack">
    <a-layout class="mt16 bgc-white">
      <a-layout-sider>
        <a-row class="pos-common-title">
          岗位类型
          <a-icon type="plus" @click="addType" />
        </a-row>
        <a-menu v-model="current" mode="vertical">
          <a-menu-item v-for="item in menuData" :key="item.id" class="bbE8E8E8" @click="getSelectId(item)">
            <a-tooltip placement="rightTop">
              <template v-if="item.name.length > 8" slot="title">
                <span>{{ item.name }}（{{ item.childCount }}）</span>
              </template>
              <span class="ove" style="width: 150px; display: inline-block"> {{ item.name }}（{{ item.childCount }}） </span>
            </a-tooltip>
            <a-icon type="setting" @click.stop="editType(item)" />
          </a-menu-item>
        </a-menu>
      </a-layout-sider>
      <a-layout-content class="pl24 pr24">
        <a-row class="pos-header">
          <a-col>
            <h2>{{ name22 }}</h2>
          </a-col>
          <a-col style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap">{{ desc22 }}</a-col>
        </a-row>
        <a-row class="pt24 h84 bbE8E8E8">
          <a-input-search placeholder="输入岗位名称" style="width: 200px" @search="onSearch" />
          <a-button class="fr" type="primary" icon="plus" @click="addPos"> 新建岗位 </a-button>
        </a-row>
        <a-table row-key="id" :columns="columns" :pagination="pagination" @change="handleTableChange" :data-source="tableData">
          <template slot="empCount" slot-scope="text, record">
            <a-button size="small" type="link" @click="showEmp(record)">{{ text }}</a-button>
          </template>
          <template slot="action" slot-scope="text, record">
            <a-button type="link" @click="edit(record)">编辑</a-button>
          </template>
        </a-table>

        <a-modal v-model="empVisible" :title="`${gangNam}` + '岗位'" width="800px" @ok="handleEmpOk">
          <a-input-search
            v-model="unitSearchForm.keyWord"
            allow-clear
            class="mr12"
            placeholder="姓名或手机号"
            style="width: 180px; margin-left: 10px"
            @search="unitNameChange"
          />
          <a-table
            :data-source="empGroup"
            :columns="empList"
            :pagination="pagination2"
            style="margin-top: 50px"
            @change="handlePageChange"
          />
        </a-modal>
      </a-layout-content>
    </a-layout>
    <a-drawer
      :title="titleType"
      :width="520"
      :visible="posTypeVisible"
      :wrap-style="{ overflow: 'auto' }"
      @close="onClose('posTypeVisible')"
    >
      <a-form :form="posTypeForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="名称">
              <a-input
                v-decorator="[
                  'name',
                  {
                    rules: [{ required: true, message: '请输入名称' }]
                  }
                ]"
                placeholder="请输入名称"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="说明">
              <a-textarea v-decorator="['desc']" :rows="4" placeholder="请输入说明" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item>
              <a-input v-decorator="['id']" type="hidden" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="drawer-footer-box">
        <a-button v-if="titleType == '编辑岗位类型'" class="mr12" @click="delType">删除</a-button>
        <a-button class="mr12" @click="onClose('posTypeVisible')"> 取消 </a-button>
        <a-button type="primary" @click="addTypeSubmit">确定</a-button>
      </div>
    </a-drawer>
    <!-- 添加岗位 -->
    <a-drawer :title="title" :width="520" :visible="posVisible" :wrap-style="{ overflow: 'auto' }" @close="onClose('posVisible')">
      <a-form :form="posForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="名称">
              <a-input
                v-decorator="[
                  'name',
                  {
                    rules: [{ required: true, message: '请输入名称' }]
                  }
                ]"
                placeholder="请输入名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="岗位编号">
              <a-input v-decorator="['code']" placeholder="请输入" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="岗位类型">
              <a-select
                v-decorator="[
                  'parentId',
                  {
                    rules: [{ required: true, message: '请选择岗位类型' }]
                  }
                ]"
                placeholder="请选择岗位类型"
              >
                <a-select-option v-for="item in menuData" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-if="menuData == null || menuData.length === 0" :span="12">
            没有岗位类型？
            <a-button class="mt24" type="link" @click="addType"> 去添加 </a-button>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="岗位说明">
              <a-textarea v-model="desc" :rows="4" placeholder="请输入岗位说明" :max-length="50" />
              <a-row class="ta-right textarea-tip"> {{ desc ? desc.length : 0 }}/50字 </a-row>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item>
              <a-input v-decorator="['id']" type="hidden" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="drawer-footer-box">
        <a-button v-if="title == '编辑岗位'" class="mr12" @click="delPos"> 删除 </a-button>
        <a-button class="mr12" @click="onClose('posVisible')">取消</a-button>
        <a-button type="primary" @click="addPosSubmit">确定</a-button>
      </div>
    </a-drawer>
  </a-layout>
</template>
<script>
const columns = [
  {
    title: "岗位名称",
    dataIndex: "name",
    align: "center"
  },
  {
    title: "岗位编号",
    dataIndex: "code",
    align: "center"
  },
  {
    title: "在职人数",
    dataIndex: "empChildrenCount",
    scopedSlots: { customRender: "empCount" },

    align: "center"
  },
  {
    title: "岗位说明",
    dataIndex: "desc",
    width: 350
  },
  {
    title: "操作",
    key: "action",
    align: "center",
    scopedSlots: { customRender: "action" }
  }
];
const empList = [
  {
    title: "姓名",
    dataIndex: "name",
    width: 120
  },
  {
    title: "员工手机号",
    dataIndex: "phone",
    ellipsis: true,
    width: 120
  }
];
import {
  getPositionInTree,
  getPositionInfoListPage,
  getListPositionType,
  addPosition,
  delPosition,
  editPosition
} from "@/api/department/position";

export default {
  inject: ["reload"],
  data() {
    return {
      name22: "",
      desc22: "",
      empList,
      unitSearchForm: {},
      empGroup: [],
      gangNam: "",
      empVisible: false,
      current: [],
      companyId: "",
      parentId: "",
      selectId: "",
      menuData: [],
      tableData: [],
      targetData: {},
      columns,
      titleType: "添加岗位类型",
      title: "新建岗位",
      name: "岗位",
      desc: "岗位说明",
      posTypeForm: this.$form.createForm(this),
      posForm: this.$form.createForm(this),
      loading: false,
      posTypeVisible: false,
      posVisible: false,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        personalPeriod: null,
        editCompanyName: null,
        ticketRecord: null,
        receivableRecord: null,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      pagination2: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        pageSizeOptions: ["10", "20", "50", "100"],
        showQuickJumper: true,
        showSizeChanger: true
      }
    };
  },
  computed: {},
  created() {
    this.companyId = this.$store.state.hr.companyId;
    getPositionInTree({ companyId: this.companyId }).then((res) => {
      this.parentId = res.data[0].id;
    });

    this.init();
  },
  methods: {
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.loadData();
    },
    handlePageChange(pagination, filters, sorter) {
      this.pagination2.current = pagination.current;
      this.pagination2.pageSize = pagination.pageSize;
    },
    unitNameChange(e) {
      if (e === "") {
        this.empGroup = this.empRecord.empChildrenList;
        this.pagination2.current = 1;

        this.pagination2.total = this.empRecord.empChildrenList.length;
      } else {
        this.empGroup = [];
        for (var i = 0; i < this.empRecord.empChildrenList.length; i++) {
          if (
            (this.empRecord.empChildrenList[i].name + "").indexOf(e + "") !== -1 ||
            (this.empRecord.empChildrenList[i].phone + "").indexOf(e + "") !== -1
          ) {
            this.empGroup.push(this.empRecord.empChildrenList[i]);
          }
        }
        this.pagination2.current = 1;
        this.pagination2.total = this.empGroup.length;
      }
    },
    showEmp(record) {
      this.empRecord = record;
      this.unitSearchForm = {};
      this.empVisible = true;
      this.gangNam = record.name;
      this.empGroup = this.empRecord.empChildrenList;
      this.pagination2.current = 1;
      this.pagination2.total = this.empRecord.empChildrenList.length;
    },
    handleEmpOk() {
      this.empVisible = false;
    },
    textChange(e, b) {},
    init(deleteId) {
      getListPositionType(this.companyId).then((res) => {
        this.menuData = res.data;
        if (this.menuData === null || this.menuData.length === 0) {
          this.targetData = {};
          this.current = [];
          this.selectId = "";
          this.name = "";
          this.desc = "";
        } else if (this.current.length === 0 || deleteId === this.selectId) {
          this.targetData = this.menuData[0];
          this.current = [this.targetData.id];
          this.selectId = this.targetData.id;
          this.name22 = this.targetData.name;
          this.desc22 = this.targetData.desc;
        }
        this.loadData();
      });
    },
    loadData(text) {
      getPositionInfoListPage({
        companyId: this.companyId,
        parentId: this.selectId,
        type: 1,
        name: text,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      }).then((res) => {
        this.tableData = res.data.entities;
        this.pagination.total = res.data && res.data.entityCount;
      });
    },
    getSelectId(target) {
      this.targetData = target;
      this.name22 = target.name;
      this.desc22 = target.desc;
      this.selectId = target.id;
      this.loadData();
    },
    delType() {
      var that = this;
      this.$confirm({
        title: `确定删除岗位类型 ${that.posTypeForm.getFieldValue("name")} 吗`,
        onOk() {
          const deleteId = that.posTypeForm.getFieldValue("id");
          delPosition({ id: deleteId }).then((res) => {
            that.$notification["success"]({
              message: "success",
              description: "删除成功"
            });
            that.posTypeVisible = false;
            that.init(deleteId);
          });
        }
      });
    },
    delPos() {
      var that = this;
      this.$confirm({
        title: `确定删除岗位 ${that.posForm.getFieldValue("name")} 吗`,
        onOk() {
          delPosition({ id: that.posForm.getFieldValue("id") }).then((res) => {
            that.$notification["success"]({
              message: "success",
              description: "删除成功"
            });
            that.onClose("posVisible");
            that.init();
          });
        }
      });
    },
    addType() {
      this.titleType = "添加岗位类型";
      this.posTypeVisible = true;
      this.posTypeForm.resetFields();
    },
    editType(data) {
      this.titleType = "编辑岗位类型";
      this.posTypeVisible = true;
      setTimeout(() => {
        this.posTypeForm.setFieldsValue({
          name: data.name || this.targetData.name,
          id: data.id || this.targetData.id,
          desc: data.desc
        });
      }, 10);
    },
    addTypeSubmit(e) {
      var that = this;
      e.preventDefault();
      this.posTypeForm.validateFields((err, values) => {
        if (!err) {
          values.level = 2;
          values.parentId = this.parentId;
          values.sort = 0;
          values.type = 2;
          values.companyId = this.companyId;

          if (this.titleType === "添加岗位类型") {
            addPosition(values).then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "添加成功"
              });
              this.onClose("posTypeVisible");
              this.init();
            });
          } else {
            editPosition(values).then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "编辑成功"
              });
              this.name22 = values.name;
              this.desc22 = values.desc;

              this.onClose("posTypeVisible");
              // that.reload()
              that.init();
            });
          }
        }
      });
    },
    addPos() {
      this.desc = "";
      this.title = "新建岗位";
      this.posVisible = true;
      this.posForm.resetFields();
      setTimeout(() => {
        this.posForm.setFieldsValue({
          parentId: this.selectId
        });
      }, 300);
    },

    edit(data) {
      this.title = "编辑岗位";
      this.posVisible = true;
      setTimeout(() => {
        this.desc = data.desc;
        this.posForm.setFieldsValue({
          name: data.name,
          id: data.id,
          parentId: this.selectId,
          code: data.code
        });
      }, 10);
    },
    addPosSubmit(e) {
      e.preventDefault();
      this.posForm.validateFields((err, values) => {
        if (!err) {
          values.level = 3;
          values.sort = 0;
          values.type = 1;
          values.companyId = this.companyId;
          if (this.title === "新建岗位") {
            values.desc = this.desc;
            addPosition(values).then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "添加成功"
              });
              this.$store.dispatch("company/loadPositionsAct", this.companyId);
              this.onClose("posVisible");
              this.init();
            });
          } else {
            values.desc = this.desc;
            editPosition(values).then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "编辑成功"
              });
              this.$store.dispatch("company/loadPositionsAct", this.companyId);
              this.onClose("posVisible");
              this.loadData();
            });
          }
        }
        setTimeout(() => this.init(), 200);
      });
    },
    onClose(tag) {
      this[tag] = false;
    },

    onSearch(text) {
      this.pagination.current = 1;
      this.loadData(text);
    }
  }
};
</script>
<style lang="scss">
.positionBox {
  .pos-common-title {
    height: 48px;
    line-height: 48px;
    color: #000;
    font-size: 20px;
    i {
      float: right;
      padding-right: 24px;
      line-height: 48px;
    }
  }
  .ant-menu {
    margin-top: -48px;
    padding-top: 48px;
    height: calc(100% - 24px);
  }
  .ant-menu-item {
    padding-left: 0;
    padding-right: 0;
    .anticon {
      float: right;
      padding-right: 14px;
      line-height: 42px;
      // position: absolute;
    }
  }

  .pos-header {
    h2 {
      font-size: 20px;
      display: inline;
    }
    height: 88px;
    line-height: 30px;
    padding-top: 14px;
    border-bottom: 1px solid #e8e8e8;
  }
}
</style>
